package com.cyz.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import com.cyz.mapper.ReserveMapper;
import com.cyz.mapper.TypeMapper;
import com.cyz.mapper.UserMapper;
import com.cyz.pojo.Paging;
import com.cyz.pojo.Reserve;
import com.cyz.pojo.User;
import com.cyz.service.ReserveService;

/**
 * @author 陈雅珠
 * 预约服务层实现类
 */
@Service("reserveServiceImpl")
public class ReserveServiceImpl implements ReserveService,ApplicationListener<ContextRefreshedEvent> {

	@Resource(name="reserveMapper")
	private ReserveMapper reserveMapper;
	@Resource(name="paging")
	private Paging<Reserve> paging;
	@Resource(name="userMapper")
	private UserMapper userMapper;
	@Resource(name="typeMapper")
	private TypeMapper typeMapper;
	
	/**
	 * 以分页的形式获取预约列表
	 * @param map 可选：startTime 开始时间 ，endTime 结束时间， page 当前页 ，pageSize 页面大小，idNumber 身份证号码
	 * @return 存放着预约列表的paging对象
	 */
	@Override
	public Paging<Reserve> getReserve(Map map) {
		Integer page = (Integer)map.get("page"); 
		Integer pageSize = (Integer)map.get("pageSize");
		map.put("start",(page-1)*pageSize); //起始位置
		map.put("offset",pageSize); //偏移量
		if(map.get("idNumber").equals("")) { //如果没有传入身份证号码
			map.put("userId",null); //置空
		} else { 
			User user = userMapper.getUserByIdNumber((String)map.get("idNumber"));
			if(null != user) {
				map.put("userId",user.getId()); //置空
			} else {
				map.put("userId","0"); //置空
			}
		}

		List<Reserve> list = reserveMapper.getReserve(map);
		paging.setTotalCount(reserveMapper.getReserveTotalCount(map));
		System.out.println(reserveMapper.getReserveTotalCount(map));
		paging.setList(list);
		paging.setPageSize(pageSize);
		paging.setCurrentPage(page);
		return paging;
	}

	/**
	 * 删除预约
	 * @param reserveId 预约编号
	 * @return void
	 */
	@Override
	public void deleteReserve(Integer reserveId) {
		reserveMapper.deleteReserve(reserveId);
	}

	/**
	 * 更新预约
	 * @param reserve 预约对象
	 * @return void 
	 */
	@Override
	public void updateReserve(Reserve reserve) {
		
	
	}

	/**
	 * 服务器启动时去初始化预约列表
	 */
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		reserveMapper.reserveInit();
	}

	/**
	 * 审核通过预约
	 * @param reserveId 预约编号
	 */
	@Override
	public void approveReserve(Integer reserveId) {
		Reserve reserve = reserveMapper.getReserveById(reserveId);
		reserve.setState(4);
		reserveMapper.updateReserve(reserve);
	}
	
}
